var planet;

jQuery(function($) {

  awPlus.fspp_alerting = false;

  if ($('td[bgcolor=#602020]').size() > 0) {
    return;
  }

  var p = $('body table:eq(2) tr td');

  planet = {
    id: parseInt(document.location.href.match(/[0-9]+$/)[0]),
    name: $(p.get(0)).html(),

    hf_lvl: parseInt($(p.get(10)).attr({id:'hf_lvl',nowrap:'nowrap'}).html()),
    hf_rmn: parseInt($(p.get(12)).attr({id:'hf_rmn',nowrap:'nowrap',align:'right'}).html()),
    rf_lvl: parseInt($(p.get(14)).attr({id:'rf_lvl',nowrap:'nowrap'}).html()),
    rf_rmn: parseInt($(p.get(16)).attr({id:'rf_rmn',nowrap:'nowrap',align:'right'}).html()),
    gc_lvl: parseInt($(p.get(18)).attr({id:'gc_lvl',nowrap:'nowrap'}).html()),
    gc_rmn: parseInt($(p.get(20)).attr({id:'gc_rmn',nowrap:'nowrap',align:'right'}).html()),
    rl_lvl: parseInt($(p.get(22)).attr({id:'rl_lvl',nowrap:'nowrap'}).html()),
    rl_rmn: parseInt($(p.get(24)).attr({id:'rl_rmn',nowrap:'nowrap',align:'right'}).html()),
    sb_lvl: parseInt($(p.get(26)).attr({id:'sb_lvl',nowrap:'nowrap'}).html()),
    sb_rmn: parseInt($(p.get(28)).attr({id:'sb_rmn',nowrap:'nowrap',align:'right'}).html()),

    pp: parseInt($(p.get(30)).attr('id', 'pp').html()),

    tr:     parseInt($(p.get(38)).attr({id:'tr_tt'}).html()),
    tr_val: parseInt($(p.get(40)).attr({id:'tr_rmn',align:'left'}).html().replace(/[0-9]+\/([0-9]+)/,'$1')),
    cs:     parseInt($(p.get(42)).attr({id:'cs_tt'}).html()),
    cs_val: parseInt($(p.get(44)).attr({id:'cs_rmn',align:'left'}).html().replace(/[0-9]+\/([0-9]+)/, '$1')),
    ds:     parseInt($(p.get(46)).attr({id:'ds_tt'}).html()),
    ds_val: parseInt($(p.get(48)).attr({id:'ds_rmn',align:'left'}).html().replace(/[0-9]+\/([0-9]+)/, '$1')),
    cr: 0,
    cr_val: 0,
    bs: 0,
    bs_val: 0,

    getRemain: function(item) {
      switch (item) {
        case 'hf': return this.hf_rmn;
        case 'rf': return this.rf_rmn;
        case 'gc': return this.gc_rmn;
        case 'rl': return this.rl_rmn;
        case 'sb': return this.sb_rmn;

        case 'tr': return this.tr_val;
        case 'cs': return this.cs_val;
        case 'ds': return this.ds_val;
        case 'cr': return this.cr_val;
        case 'bs': return this.bs_val;
      }
    },

    getLevel: function(item) {
      switch (item) {
        case 'hf': return this.hf_lvl;
        case 'rf': return this.rf_lvl;
        case 'gc': return this.gc_lvl;
        case 'rl': return this.rl_lvl;
        case 'sb': return this.sb_lvl;
      }
    },

    spend: function(item, pp) {
      if (!confirm('Do you really want spend '+pp+' points in '+item+'?')) {
        return false;
      }

      var _items = {
        'hf':'farm',
        'rf':'fabrik', 
        'gc':'kultur', 
        'rl':'forschungslabor', 
        'sb':'starbase', 
        'tr':'infantrieschiff', 
        'cs':'kolonieschiff', 
        'ds':'destroyer', 
        'cr':'cruiser', 
        'bs':'battleship'
      }

      $.post(
        '/0/Planets/submit.php',
        {points: pp, produktion: _items[item], i: this.id},
        function() {
          window.location.reload();
        }
      );
      return true;
    }
  }

  $('#awplus_content table:eq(0) tr:gt(12) td:contains(Cruiser)').parent().find('td:eq(1), td:eq(3)').each(function(i) {
    switch(i) {
      case 0: planet.cr = parseInt($(this).attr({id:'cr_tt'}).text()); break;
      case 1: planet.cr_val = parseInt($(this).attr({id:'cr_rmn',align:'left'}).text().replace(/[0-9]+\/([0-9]+)/, '$1')); break;
    }
  });
  $('#awplus_content table:eq(0) tr:gt(12) td:contains(Battleship)').parent().find('td:eq(1), td:eq(3)').each(function(i) {
    switch(i) {
      case 0: planet.bs = parseInt($(this).attr({id:'bs_tt'}).text()); break;
      case 1: planet.bs_val = parseInt($(this).attr({id:'bs_rmn',align:'left'}).text().replace(/[0-9]+\/([0-9]+)/, '$1')); break;
    }
  });

  if (planet.pp <= 0) return this;

  // A brincadeira comeca aqui!

  var items = ['hf','rf','gc','rl','sb'];

  for (i in items) {
    var item = items[i];
    
    $('#'+item+'_rmn')
      .wrapInner('<div id="'+item+'_rmn_val" style="float:right; margin-right: 3px;"></div>')
      .prepend('<div id="'+item+'_cart" class="ui-state-default ui-corner-all ap_lvlup" style="cursor: pointer; float:right; padding: 0px 2px 0px 2px;"><span class="ui-icon ui-icon-cart" /></div>');
        
    $('#'+item+'_cart')
      .hover(
        function() { $(this).addClass('ui-state-hover'); },
        function() { $(this).removeClass('ui-state-hover'); }
      )
      // Open/Close cart options
      .click(function() {
        $(this).removeClass('ui-corner-all').addClass('ui-corner-right').addClass('ui-state-active');
        
        var id = this.id.replace(/_cart/, '');
        var item = id;
        var lvlup = $('#'+id+'_lvlup');
        
        // If cart itens not built.
        if (lvlup.size() == 0) {
          $('#'+id+'_rmn').append('<div id="'+id+'_lvlup" class="ui-state-active ui-corner-left" style="position: absolute; display: none; padding-left: 3px;"></div>');
          lvlup = $('#'+id+'_lvlup');
          lvlup.data('ap_item', id);

          lvlup.mouseout(function(e) {
            if ($(e.relatedTarget).hasClass('.ap_lvlup')) return;
            $('#'+$(this).data('ap_item')+'_cart');
          });
          
          // preparing html with levels
          var _html;          
          var spend_value = planet.getRemain(item);
          var level = planet.getLevel(item)+1;
          while (spend_value <= planet.pp) {
            _html = '<span id="'+item+'_lvlup_'+level+'" class="ap_lvlup ui-state-default">&nbsp;+'+level+'&nbsp;</span>';
            lvlup.prepend(_html);
            $('#'+item+'_lvlup_'+level).data('ap_spend_pp', spend_value);
            
            spend_value += awPlus.levels_pp[++level];
          }
          
          lvlup.prepend('<span id="'+item+'_lvlup_all" class="ap_lvlup ui-state-default">&nbsp;All&nbsp;</span>');
          $('#'+item+'_lvlup_all').data('ap_spend_pp', planet.pp);
          
          $('#'+item+'_lvlup .ap_lvlup')
            .css('cursor', 'pointer')
            .hover(
              function() { $(this).addClass('ui-state-hover') },
              function() { $(this).removeClass('ui-state-hover') }
            )
            .click(function() {
              $(this).addClass('ui-state-focus');
              planet.spend(item, $(this).data('ap_spend_pp'));
              $(this).removeClass('ui-state-focus');
            });
          
          var wid = lvlup.width();
          lvlup.css({'height': 16, 'width': wid});
        }
        
        if (lvlup.is(':visible')) {
          lvlup.hide('slide', {'direction': 'right'}, 200);
          $(this).removeClass('ui-corner-right').addClass('ui-corner-all').removeClass('ui-state-active');
        }
        else {      
          var pos = $(this).offset();      
          lvlup
            .css({'top': pos.top, 'left': pos.left - wid - 3})
            .show('slide', {'direction': 'right'}, 200);
        }
      });
  }


  // -- FLEETS -----------------------------------------------

  var items = ['tr','cs','ds','cr','bs'];

  for (i in items) {
    var item = items[i];
    var total = Math.floor( planet.pp / planet[item+'_val'] );
    var rmn = $('#'+item+'_rmn').append('&nbsp;<span style="font-size: 10px">(<span id="'+item+'_fspptt">'+total+'</span>)</span>');
    if (total == 0) continue;
    
    rmn
      .wrapInner('<div id="'+item+'_rmn_val" style="float:right; margin-right: 3px;"></div>')
      .prepend('<div id="'+item+'_cart" class="ui-state-default ui-corner-all" style="cursor: pointer; float:right; padding: 0px 2px 0px 2px;"><span class="ui-icon ui-icon-cart" /></div>');
      
    $('#'+item+'_cart')
      .hover(
        function() { $(this).addClass('ui-state-hover'); },
        function() { $(this).removeClass('ui-state-hover'); }
      )
      // Open/Close cart options
      .click(function() {
        $(this).removeClass('ui-corner-all').addClass('ui-corner-right').addClass('ui-state-active');
        
        var id = this.id.replace(/_cart/, '');
        var item = id;
        var fleet = $('#'+id+'_fleet');
        
        // If cart itens not built.
        if (fleet.size() == 0) {
          $('#'+id+'_rmn').append('<div id="'+id+'_fleet" class="ui-state-active ui-corner-left" style="position: absolute; display: none; padding-left: 3px;"></div>');
          fleet = $('#'+id+'_fleet');
          
          // preparing html with fields
          fleet.append('<span id="'+item+'_fleet_all" class="ap_fleet ui-state-default">&nbsp;'+$('#'+item+'_fspptt').text()+'&nbsp;</span>');
          
          fleet.append('<span id="'+item+'_fleet_field_box" class="ui-state-default"><input id="'+item+'_fleet_field" value="0" style="font-size: 10px; width: 30px; height: 17px; border: 1px solid #000; background-color: #4A4A4A; text-align: center;" /></span>');
          
          
          $('#'+item+'_fleet_all')
            .css('cursor', 'pointer')
            .hover(
              function() { $(this).addClass('ui-state-hover') },
              function() { $(this).removeClass('ui-state-hover') }
            )
            .click(function() {
              $(this).addClass('ui-state-focus');
              planet.spend(item, parseInt($('#'+item+'_fspptt').text()) * planet.getRemain(item));
              $(this).removeClass('ui-state-focus');
            });
          
          $('#'+item+'_fleet_field').keyup(function(e) {
            this.value = this.value.replace(/[^0-9]+/g, '');
            var tt_fleets = parseInt(this.value == '' ? 0 : this.value);

            if (e.keyCode == 13 && !awPlus.fspp_alerting && tt_fleets > 0) {
              awPlus.fspp_alerting = true;
              var item = this.id.replace(/^(..)_fleet_field/, '$1');
              var pp = planet[item+'_val'] * tt_fleets;
              var total = parseInt($('#'+item+'_fspptt').text());

              if (tt_fleets > total) {
                alert('Choose a value lower or equal than '+ total+'.');
                this.value = '0';
                awPlus.fspp_alerting = false;
                return;
              }

              if (!planet.spend(item, pp)) {
                awPlus.fspp_alerting = false;
                return;
              }

              this.disabled = true;
              $('#'+item+'_fsppv').hide();
            }
          });
          
          var wid = fleet.width() + 2;
          fleet.css({'height': 16, 'width': wid});
        }
        
        if (fleet.is(':visible')) {
          fleet.hide('slide', {'direction': 'right'}, 200);
          $(this).removeClass('ui-corner-right').addClass('ui-corner-all').removeClass('ui-state-active');
        }
        else {
          var wid = fleet.width();
          var pos = $(this).offset();      
          fleet
            .css({'top': pos.top, 'left': pos.left - wid - 5})
            .show('slide', {'direction': 'right'}, 200, function() {
              $('#'+item+'_fleet_field')[0].select();
            });
        }
      });
  }

});
